﻿using System;
using System.Linq;
using System.Reflection;

namespace SeleniumToolkit.Core
{
    /// <summary>
    /// Utility functions to copy settings from attributes
    /// </summary>
    public class SessionInfoHelper
    {
        /// <summary>
        /// Read attributes from Type
        /// </summary>
        /// <param name="info">The target to copy settings into</param>
        /// <param name="type">The source type that contains WebFixtureAttribute settings</param>
        public static void CopyAttributes(ISessionInfo info, Type type)
        {
            WebFixtureAttribute attrib = type.GetCustomAttributes(true).OfType<WebFixtureAttribute>().SingleOrDefault();
            CopyAttributes(info, attrib);
        }

        /// <summary>
        /// Reads attributes from Method
        /// </summary>
        /// <param name="info">The target to copy settings into</param>
        /// <param name="method">The source method that contains WebTestAttribute settings</param>
        public static void CopyAttributes(ISessionInfo info, MethodInfo method)
        {
            // configure from attribute
            WebTestAttribute attrib = method.GetCustomAttributes(false).OfType<WebTestAttribute>().SingleOrDefault();
            CopyAttributes(info, attrib);
        }

        /// <summary>
        /// Copies settings from attribute into target object
        /// </summary>
        /// <param name="info"></param>
        /// <param name="attribute"></param>
        private static void CopyAttributes(ISessionInfo info, WebTestAttribute attribute)
        {
            if (attribute == null)
                return;

            if (attribute.BaseUrl != null)
            {
                info.BaseUrl = attribute.BaseUrl;
            }
            if (attribute.DefaultBrowser != null)
            {
                info.DefaultBrowser = attribute.DefaultBrowser;
            }
            if (attribute.Timeout > 0)
            {
                info.Timeout = attribute.Timeout.ToString();
            }
        }
    }
}
